<template>
  <n-drawer
    v-model:show="show"
    :style="style"
    :to="to"
    :width="width"
    :height="height"
    :placement="placement"
    @update:show="onUpdateShow"
  >
    <n-drawer-content :title="title" :closable="closable" :header-style="headerStyle" :body-style="bodyStyle">
      <template v-if="$slots.header" #header>
        <slot name="header" />
      </template>
      <slot />
      <template v-if="$slots.footer" #footer>
        <slot name="footer" />
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts">
  import { defineComponent, reactive, toRefs, watch } from 'vue'
  import { NDrawer, NDrawerContent } from 'naive-ui'

  export default defineComponent({
    name: 'XDrawer',
    components: {
      NDrawer,
      NDrawerContent
    },
    props: {
      title: {
        type: String,
        default: '标题'
      },
      placement: {
        type: String,
        default: 'right'
      },
      to: {
        type: String,
        default: 'body'
      },
      style: {
        type: [String, Object],
        default: ''
      },
      width: {
        type: [Number, String],
        default: 600
      },
      height: {
        type: Number,
        default: 300
      },
      visible: {
        type: Boolean,
        default: false
      },
      closable: {
        type: Boolean,
        default: true
      },
      headerStyle: {
        type: [String, Object],
        default: ''
      },
      bodyStyle: {
        type: [String, Object],
        default: 'overflow: auto'
      }
    },
    emits: ['update:visible'],
    setup($props, { emit: $emit }) {
      const $state = reactive({
        ...toRefs($props),
        show: $props.visible
      })

      // watch
      watch(
        () => $props.visible,
        (value: boolean) => {
          $state.show = value
        }
      )

      // 抽屉显示状态改变时执行的回调函数
      const onUpdateShow = (show: boolean) => {
        $emit('update:visible', show)
      }

      return {
        ...toRefs($state),
        onUpdateShow
      }
    }
  })
</script>

<style></style>
